import { Component, Label, Node, _decorator } from 'cc';
import { GameMgr } from '../game/GameMgr';
const { ccclass, property } = _decorator;

@ccclass("UIRank")
export class UIRank extends Component {

    @property(Node)
    ranks: Node;
    @property(Node)
    myRank: Node;

    protected update(dt: number) {
        const { snakeMgr, snakeId } = GameMgr.ins;
        const snakes = Array.from(snakeMgr.snakeMap.values()).sort((a, b) => b.data.score - a.data.score);
        for (let i = 0; i < 10; ++i) {
            const snake = snakes[i];
            const rankItem = this.ranks.children[i];
            rankItem.active = !!snake;
            if (snake) {
                this.setRank(
                    rankItem,
                    i + 1,
                    snake.data.name,
                    snake.data.score
                );
            }
        }

        const mySnake = snakeMgr.snakeMap.get(snakeId);
        if (mySnake) {
            this.setRank(
                this.myRank,
                snakes.indexOf(mySnake) + 1,
                mySnake.data.name,
                mySnake.data.score
            );
        }
    }

    setRank(rankItem: Node, rank: number, name: string, score: number) {
        rankItem.children[0].getComponent(Label).string = rank + "";
        rankItem.children[1].getComponent(Label).string = name;
        rankItem.children[2].getComponent(Label).string = Math.floor(score) + "";
    }

}